//列表
import { Table, TableProps } from 'antd'
import type { ColumnsType } from 'antd/lib/table'
import React, { useState, useEffect } from 'react'
interface ListProps<T> {
  dataSource: T[] //列表显示的数据
  columns: ColumnsType<T | any> //列表的表头
  loading: boolean //加载效果
  rowKey: string //列中的key
  select?: boolean //是否开启复选框
  onListSelectChange?: (
    SelectedRow: T[],
    newSelectedRowKeys: React.Key[]
  ) => void //复选框中选择的值
  selectedRowsData?: T[] //选中的值
  selectedRowKeysData?: React.Key[] //选中值的key
  width?: number //列表宽度
  defaultExpandAllRows?: boolean //初始时，是否展开所有行
  height?: number //列表高度,
  onChange?: TableProps<T>['onChange'] //列表修改
}

function List<T>(props: ListProps<T>) {
  const {
    dataSource,
    columns,
    loading,
    rowKey,
    select = false,
    onListSelectChange,
    selectedRowsData,
    selectedRowKeysData,
    width,
    defaultExpandAllRows = false,
    height,
    onChange
  } = props
  const [selectedRowKeys, setSelectedRowKeys] = useState<
    React.Key[]
  >(selectedRowKeysData as React.Key[]) // 表格选择框选中的数据
  const [selectedRows, setSelectedRows] = useState<T[]>(
    selectedRowsData as T[]
  ) // 表格选择框选中的数据内容

  useEffect(() => {
    //清空选择
    if (
      !selectedRowsData?.length &&
      !selectedRowKeysData?.length
    ) {
      setSelectedRowKeys([])
      setSelectedRows([])
    }
  }, [selectedRowsData, selectedRowKeysData])
  useEffect(() => {}, [columns])
  // 列选择框事件
  const onSelectChange = (
    newSelectedRowKeys: React.Key[],
    SelectedRow: any
  ) => {
    setSelectedRows(SelectedRow)
    setSelectedRowKeys(newSelectedRowKeys)
    if (onListSelectChange) {
      onListSelectChange(SelectedRow, newSelectedRowKeys)
    }
  }
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange
  }
  return (
    <Table
      rowKey={rowKey}
      rowSelection={select ? rowSelection : undefined}
      columns={columns}
      dataSource={dataSource}
      bordered
      loading={loading}
      scroll={{
        x: width ? width : 1300,
        y: height ? height : undefined
      }}
      pagination={false}
      defaultExpandAllRows={defaultExpandAllRows}
      onChange={onChange}
    />
  )
}

export default List
